package com.hmy.security.controller;


import com.hmy.security.entity.Roles;
import com.hmy.security.entity.RolesUser;
import com.hmy.security.service.IRolesUserService;
import com.hmy.security.vo.UserRolesVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.Min;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户身份表 前端控制器
 * </p>
 *
 * @author hmy
 * @since 2023-01-30
 */
@RestController
@RequestMapping("/roles")
@Validated
public class RolesController {

    @Autowired
    private IRolesUserService rolesUserService;

    @GetMapping("/list")
    List<Roles> getUserRole(@Min(value = 1, message = "用户id必须大于0") Long uid) {
        UserRolesVo userRolesVo = rolesUserService.getRolesByUid(uid);
        return userRolesVo.getRoles();
    }

    /**
     * 更改用户权限
     * hasRole源码 {@link org.springframework.security.access.expression.SecurityExpressionRoot}
     * 权限： "部长" - 自定义权限表roles中自定义的角色名 在{@link com.hmy.security.security.service.UserDetailServiceImpl}处被存储至List<SimpleGrantedAuthority>中
     * @param uid 用户id
     * @param rid 权限id
     * @return {@link Boolean}
     */
    @PreAuthorize("hasRole('部长')")
    @PostMapping("/change")
    Boolean changeUserRole(@Min(value = 1, message = "用户id必须大于0") Long uid,
                           @Min(value = 1, message = "身份id必须大于0") Integer rid) {
        List<RolesUser> roles = rolesUserService.lambdaQuery()
                .eq(RolesUser::getUid, uid)
                .list();
        for(RolesUser r: roles) {
            if (r.getRoleId().equals(rid)) {
                return true;
            }
        }
        rolesUserService.removeByIds(roles.stream().map(RolesUser::getId).collect(Collectors.toList()));
        RolesUser rolesUser = new RolesUser();
        rolesUser.setRoleId(rid);
        rolesUser.setUid(uid);
        return rolesUserService.save(rolesUser);

    }


}
